package com.hsc.www.server;

import com.hsc.www.server.userAccount.UserAccountEntity;
import com.hsc.www.server.userAccount.UserAccountService;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashSet;

@Component
public class MyJdbcUserDetailsService implements UserDetailsService {

    private UserAccountService userAccountService;

    public MyJdbcUserDetailsService(UserAccountService userAccountService) {
        this.userAccountService = userAccountService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {


        UserAccountEntity userAccountEntity = userAccountService.selectByUsername(username);
        if (userAccountEntity ==null){
            throw new UsernameNotFoundException("用户名不存在！");
        }

        Collection<SimpleGrantedAuthority> simpleGrantedAuthorityCollection=new HashSet<>();
        for (String role: userAccountEntity.getRoles()) {
            simpleGrantedAuthorityCollection.add(new SimpleGrantedAuthority(role));
        }

        UserDetails userDetails = new User(userAccountEntity.getUsername(), userAccountEntity.getPassword(), simpleGrantedAuthorityCollection);

        return  userDetails;
    }
}
